/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.chanceit.ssss.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.http.AjaxCallBack;

import org.gl.customview.PullToRefreshView;
import org.gl.customview.PullToRefreshView.OnFooterRefreshListener;
import org.gl.customview.PullToRefreshView.OnHeaderRefreshListener;
import org.gl.utils.lg;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.chanceit.ssss.activity.R;
import com.chanceit.ssss.adapters.SimpleSessionAdapter;
import com.chanceit.ssss.common.IntentExtraDataKey;

/**
 * the all carder list that has ordered and state is 0.
 * 
 * @author Administrator
 * 
 */
public class MessageInfoListFragment extends BaseFragment implements
		OnItemClickListener, OnHeaderRefreshListener, OnFooterRefreshListener {
	OnListFragmentSelectedListener mCallback;
	List<Map<String, Object>> contents = new ArrayList<Map<String, Object>>();
	// String[] keys = new String[] { "userName", "content", "carName",
	// "reserveTime", "handler", "applyTime" };
	String[] keys = new String[] { "userName", "handleTime", "handler",
			"content", "", "applyTime" };
	protected JSONArray userListJosnAry = new JSONArray();
	BaseAdapter adapter;
	String type;
	int messageId;
	int page = 1;

	// The container Activity must implement this interface so the frag can
	// deliver messages
	public interface OnListFragmentSelectedListener {
		/** Called by HeadlinesFragment when a list item is selected */
		public void onArticleSelected(int position);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	ListView listView;
	TextView tv_titleConent;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.message_info_list, container, false);
		listView = (ListView) view.findViewById(R.id.order_carer_lv);
		listView.setOnItemClickListener(this);
		mPullToRefreshView = (PullToRefreshView) (view
				.findViewById(R.id.main_pull_refresh_view));
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);
		type = getActivity().getIntent().getStringExtra(
				IntentExtraDataKey.MESSAGE_INFO_TYPE);
		messageId = getActivity().getIntent().getIntExtra(
				IntentExtraDataKey.MESSAGE_INFO_ID, -1);
		tv_titleConent = (TextView) view.findViewById(R.id.title_tv_content);
		initData(type, messageId);
		return view;
	}

	private void initData(String type, int messageId2) {
		if (adapter != null && userListJosnAry != null
				&& userListJosnAry.length() > 0) {
			setListAdapter(adapter);
			lg.i(TAG, "resotre the fragment");
			return;
		}
		getdata(type, messageId2, null);

	}

	private void getdata(String type, int messageId2, Integer _page) {
		if (type != null && type.equals(IntentExtraDataKey.COMPLAINTID)) {// 投诉
			// keys = new String[] { "userName", "content", "carName",
			// "reserveTime", "handler", "applyTime" };
			keys = new String[] { "userName", "handleTime", "handler",
					"content", "", "applyTime" };
			tv_titleConent.setText(getActivity().getString(R.string.messagecenter_complain));
			getComplaintMessageInfo(messageId2, _page);
		} else if (type != null && type.equals(IntentExtraDataKey.RESERVEID)) {// 预约
			// keys = new String[] { "userName", "content", "carName",
			// "identifier", "handler", "applyTime" };
			keys = new String[] { "userName", "handleTime", "handler",
					"content", "", "applyTime" };
			getReserveMessageInfo(messageId2, _page);
			tv_titleConent.setText(getActivity().getString(R.string.messagecenter_order));
		} else {
			Toast.makeText(getActivity(), "unvalue message id&type",
					Toast.LENGTH_SHORT).show();
		}
	}

	private void getReserveMessageInfo(int messageId2, Integer page) {
		ds.getReserveReplyList(page, messageId2, mAjaxCallBack);
	}

	private void getComplaintMessageInfo(int messageId2, Integer page) {
		ds.getComplaintReplyList(page, messageId2, mAjaxCallBack);
	}

	PullToRefreshView mPullToRefreshView;

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {

			@Override
			public void run() {
				// page++;
				// getdata(type, messageId,page);
				Toast.makeText(getActivity(), "not any more",
						Toast.LENGTH_SHORT).show();
				mPullToRefreshView.onFooterRefreshComplete();
			}
		}, 1000);
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {

			@Override
			public void run() {
				page = 1;
				getdata(type, messageId, page);
				// 设置更新时间
				// mPullToRefreshView.onHeaderRefreshComplete("最近更新:01-23 12:01");
				mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1000);

	}

	AjaxCallBack<String> mAjaxCallBack = new AjaxCallBack<String>() {
		@Override
		public void onStart() {
			super.onStart();
			loading();
		}

		@Override
		public void onFailure(Throwable t, int errorNo, String strMsg) {
			// TODO Auto-generated method stub
			super.onFailure(t, errorNo, strMsg);
			loadFailed(strMsg);
		}

		public void onSuccess(String t) {
			lg.i(TAG, t);
			int code = 0;
			String mesage = "";
			if (getActivity()==null) {
				return;
			}
			try {
				JSONArray newJsonArray = new JSONArray(t);
				contents.removeAll(contents);
				if (page <= 1) {// 如果当前页码为<=1 说明是第一次加载 清除以前的旧数据
					userListJosnAry = null;
					userListJosnAry = newJsonArray;
				} else {// 否则就是加载更多的分页数据,把新的数据添加到集合中
					for (int i = 0; i < newJsonArray.length(); i++) {
						userListJosnAry.put(newJsonArray.opt(i));
					}
				}
				int count = userListJosnAry.length();
				for (int i = 0; i < count; i++) {
					Map<String, Object> map = new HashMap<String, Object>();
					JSONObject temp = userListJosnAry.getJSONObject(i);
					for (String key : keys) {
						Object o = temp.opt(key);
						if (o == null || o.toString().equals("null")) {
							o = "";
						}
						if (key.equals("applyTime") && !o.toString().equals("")) {// 使用车间时间提到原有时间
							if (type != null
									&& type.equals(IntentExtraDataKey.COMPLAINTID)) {// 投诉
								map.put("handleTime", o.toString());
							} else if (type != null
									&& type.equals(IntentExtraDataKey.RESERVEID)) {// 预约
								map.put("handleTime", o.toString());
							}

						} else if (key.equals("handler")
								&& !o.toString().equals("")) {
							map.put("userName", "");
							map.put("handler", o.toString());
						} else {
							map.put(key, o.toString());
						}
					}
					contents.add(map);
				}
				if (adapter == null) {
					if (contents.size() > 0) {
						adapter = new SimpleSessionAdapter(getActivity(),
								(List<Map<String, Object>>) contents,
								R.layout.list_item_message_box, keys,
								new int[] { R.id.textView1, R.id.textView2,
										R.id.textView3, R.id.textView4,
										R.id.textView5 });
						setListAdapter(adapter);
					}
				} else {
					adapter.notifyDataSetChanged();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				page--;
				if (code != 0) {
					loadFailed(mesage);
				} else {
					loadSuccessed();
					page++;
				}
			}

		}
	};

	protected void setListAdapter(BaseAdapter adapter) {
		if (listView != null && adapter != null) {
			listView.setAdapter(adapter);
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		if (getFragmentManager().findFragmentById(R.id.article_fragment) != null) {
			listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		// This makes sure that the container activity has implemented
		// the callback interface. If not, it throws an exception.
		try {
			mCallback = (OnListFragmentSelectedListener) activity;
		} catch (ClassCastException e) {
			lg.e(TAG,
					"this activity not implents OnListFragmentSelectedListener");
		}
	}

	@Override
	public void onItemClick(AdapterView<?> l, View v, int position, long id) {
		Toast.makeText(getActivity(), "no action", Toast.LENGTH_SHORT).show();
	}
}